//
//  HMWorkSelectStudentVC.m
//  优学荟管理系统
//
//  Created by 陈辉明 on 2017/12/26.
//  Copyright © 2017年 星道三好. All rights reserved.
//

#import "HMWorkSelectStudentVC.h"
#import "HMWorkSelectStudentCell.h"
#import "HMWorkSelectStudentModel.h"
#import "HNAssignmentVC.h"
#import "HNSelectorHomeWork.h"
@interface HMWorkSelectStudentVC ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *numLabel;
@property (weak, nonatomic) IBOutlet UIButton *allSelectButton;
@property (strong, nonatomic) NSMutableArray *selectIndexs;//多选选中的行
@property (nonatomic,strong) NSMutableArray *dataSource;
@property (nonatomic,assign) BOOL isTrue;
@property (nonatomic,assign) NSInteger page;

@end

@implementation HMWorkSelectStudentVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpTableView];
    [self setUpRefresh];
    self.title = @"选择学生";
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTargat:self action:@selector(itemAction) image:@"icon_back_student_sign" highImage:@"icon_back_student_sign"];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[LLTools createImageWithColor:ColorRGB(255, 255, 255)] forBarMetrics:(UIBarMetricsDefault)];//设置导航栏颜色
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:ColorRGB(51,51,51)}];//设置标题颜色
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:ColorRGB(255,255,255)}]; //设置标题颜色
    [self.navigationController.navigationBar setBackgroundImage:[LLTools createImageWithColor:ColorRGB(47, 204, 138)] forBarMetrics:(UIBarMetricsDefault)];//设置导航栏颜色

    [SVProgressHUD dismiss];
}


- (void)itemAction{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark --- 上拉加载和下拉刷新方法的实现
- (void)setUpRefresh{
    
    //下拉刷新
    self.tableView.mj_header  = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downRefresh)];
    //自动更改透明度
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    //进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
    //上拉加载
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upRefresh)];
    //结束头部刷新
    [self.tableView.mj_header endRefreshing];
    //结束尾部刷新
    [self.tableView.mj_footer endRefreshing];
    
    
}

/**
 *  上拉加载
 */
- (void)upRefresh{
    
    self.isTrue = NO;
    self.page++;
    [self setNetWork];
    
}
/**
 *  下拉刷新
 */

- (void)downRefresh{
    self.isTrue = YES;
    self.page = 1;
    [self setNetWork];
    
    
}



- (void)setUpTableView {
    self.tableView.contentInset = UIEdgeInsetsMake(-54, 0, 0, 0);
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
//    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:@"HMWorkSelectStudentCell" bundle:nil] forCellReuseIdentifier:@"HMWorkSelectStudentCellId"];
    self.tableView.estimatedRowHeight = 90;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.tableFooterView = [UIView new];
}

#pragma mark - tableViewDataSource,tableViewDelegate


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  self.dataSource.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HMWorkSelectStudentModel *model = self.dataSource[indexPath.row];
    HMWorkSelectStudentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HMWorkSelectStudentCellId" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = model;
  
    cell.selectButton.selected = NO;
    for (NSIndexPath *index in _selectIndexs) {
        if (index == indexPath) { //改行在选择的数组里面有记录
            cell.selectButton.selected = YES; //打勾
            break;
        }
    }
    
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //获取到点击的cell
    HMWorkSelectStudentCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell.selectButton.selected == YES) { //如果为选中状态
        cell.selectButton.selected = NO; //切换为未选中
        [self.selectIndexs removeObject:indexPath]; //数据移除
    }else { //未选中
        cell.selectButton.selected = YES; //切换为选中
        [self.selectIndexs addObject:indexPath]; //添加索引数据到数组
    }
    self.numLabel.text = [NSString stringWithFormat:@"%ld",self.selectIndexs.count];
    if (self.selectIndexs.count < self.dataSource.count) {
        self.allSelectButton.selected = NO;
    }
    if (self.selectIndexs.count == self.dataSource.count) {
        self.allSelectButton.selected = YES;
    }
}


#pragma mark - 点击事件

//点击了全选
- (IBAction)clickAllSelectBtn:(UIButton *)sender {
    //选中的数组数量等于数据数组数量,清空选中
    if (self.selectIndexs.count == self.dataSource.count) {
        [self.selectIndexs removeAllObjects];
        for (int i = 0 ; i <self.dataSource.count ; i++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            HMWorkSelectStudentCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
             cell.selectButton.selected = NO;
        }
        sender.selected = NO;
    }else {
        [self.selectIndexs removeAllObjects];
        for (int i = 0 ; i <self.dataSource.count ; i++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            HMWorkSelectStudentCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            [self.selectIndexs addObject:indexPath];
            cell.selectButton.selected = YES;
        }
        sender.selected = YES;
    }
    
    self.numLabel.text = [NSString stringWithFormat:@"%ld",self.selectIndexs.count];
    
    
}

//点击了确定事件
- (IBAction)clickSureButton:(id)sender {
   
    if (_selectIndexs.count == 0) {
        [SVProgressHUD showErrorWithStatus:@"请选择学生"];
    }else {
        
        NSMutableArray *uidArry = [NSMutableArray new];
        [uidArry removeAllObjects];
        for (NSIndexPath *indexPath in self.selectIndexs) {
            HMWorkSelectStudentModel *model = self.dataSource[indexPath.row];
            [uidArry addObject:model.uid];
        }
        if(self.isCategory)
        {
           //wen文化课选择
            HNSelectorHomeWork *vc = [HNSelectorHomeWork new];
            vc.lessonID = self.lessionId;
            vc.Uids = [uidArry componentsJoinedByString:@","];
            [self.navigationController pushViewController:vc animated:YES];
        }
        else
        {
           
            HNAssignmentVC *vc = [HNAssignmentVC new];
            vc.LessonId = self.lessionId;
            vc.type = HNAssignmentTypeOperation;
            vc.Uids = [uidArry componentsJoinedByString:@","];
            [self.navigationController pushViewController:vc animated:YES];
            
        }
       

    }
}



#pragma mark - 网络请求

- (void)setNetWork{
    
    //http://192.168.0.113:8080/StarShine/ys/assignHomework.do?action=getStudentListByTeaOrg&lessonId=862&pageNumber=1
    
    NSString *url= [NSString stringWithFormat:@"assignHomework.do?action=getStudentListByTeaOrg&lessonId=%@&pageNumber=%ld",self.lessionId,(long)self.page];
    
    NSLog(@"%@ %@",LLBaseURL(url),[AccountTool shareAccountTool].currentAccount.authCode);
    [SVProgressHUD setDefaultStyle:(SVProgressHUDStyleCustom)];
    [SVProgressHUD  setBackgroundColor:ColorRGB(4, 4, 4)];
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    [SVProgressHUD showWithStatus:LLLoading];
    
    [NetManager Get:LLBaseURL(url) Auth:YES Params:nil Success:^(id Obj) {
        
        if ([[Obj valueForKey:@"code"]integerValue] == 1000) {
            [SVProgressHUD dismiss];
            if (self.isTrue == YES) {
                [self.dataSource removeAllObjects];
                [self.selectIndexs removeAllObjects];
                self.numLabel.text = [NSString stringWithFormat:@"%ld",self.selectIndexs.count];
            }
            
            for (NSDictionary *dict in Obj[@"t"][@"dataList"]) {
                HMWorkSelectStudentModel *model = [HMWorkSelectStudentModel HMWorkSelectStudentModelWithDict:dict];
                [self.dataSource addObject:model];
            }
            
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            
        }
        
        else {
            [SVProgressHUD showErrorWithStatus:Obj[@"msg"]];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        }
        
        if (self.selectIndexs.count < self.dataSource.count) {
            self.allSelectButton.selected = NO;
        }
        if (self.selectIndexs.count == self.dataSource.count &&self.dataSource.count != 0) {
            self.allSelectButton.selected = YES;
        }
        
        
    } Fail:^(NSError *Error) {
        [SVProgressHUD showErrorWithStatus:NetErr];
        
    }];
    
    
    
    
}


-(NSMutableArray *)dataSource {
    if (_dataSource == nil) {
        _dataSource = [NSMutableArray new];
    }
    return _dataSource;
}

- (NSMutableArray *)selectIndexs {
    if (!_selectIndexs) {
        _selectIndexs = [NSMutableArray new];
    }
    return _selectIndexs;
}


@end
